<?php
uses('sanitize');
class NewzController extends AppController {

	public $name = 'Newz';
	public $uses = null;
	public $helpers = array('Html', 'Javascript', 'Form');
	public $components = array('RequestHandler', 'Cookie');

	public function beforeFilter() {
		if($this->Session->check('user')) {
			// user is logged in
			$this->user = unserialize($this->Session->read('user'));
		} else {
			// user is not logged in
			$this->Session->setFlash('You must be logged in to do that');
			$this->redirect(array('controller' => 'users', 'action' => 'login'));
		}
	}
	
	public function download($id) {
		if(empty($id)) {
			
		} else {
			$action = 'enqueuenewzbin';
			$user = $this->user;
			$this->log("user:" . var_export($user, true));
		#	$this->setQueue(_HELLA_HOST_, _HELLA_PORT_, _HELLA_USERNAME_, _HELLA_PASSWORD_, $action, $id);
			$queue_result = $this->setQueue($user['hella_uri'],
			 	$user['hella_port'],
			 	$user['hella_username'],
			 	$user['hella_pass'],
			 	$action, $id);
		}
	}
	
	
	public function setQueue ($host, $port, $user, $passwd, $action, $id) {
		$this->log(var_export(func_get_args(), true));
		App::import('Vendor', 'xmlrpc');
		 if ($id <> '')
		 	$f=new xmlrpcmsg($action, array(new xmlrpcval($id, "string")));
		 else
			$f=new xmlrpcmsg($action, "");
	         $c=new xmlrpc_client("", $host, $port);
	         $c->setCredentials($user,$passwd);
	         $c->setDebug(0);
	         $r=$c->send($f);
	         if(!$r->faultCode())
	         	//Got a valid result, decode into php variables
	         	return php_xmlrpc_decode($r->value());
	         else {
	                //Got an error, print description
	                echo "Fault: ";
	                echo "Code: " . htmlspecialchars($r->faultCode())
	                	. " Reason '" . htmlspecialchars($r->faultString()) . "'<BR>";

	         }
	}
	public function search() {
#		$newz_html = $this->Newz->findAllByKeyword('linkinpark');
#		pr($newz_html);

		$uri = 'http://v3.newzbin.com/search/query/?area=-1&fpn=p&searchaction=Go&areadone=-1&feed=rss&q=' 
			. urlencode($this->params['url']['data']['Newz']['query']);

		
	//	var_dump($rss_php->getItems());
		if(empty($this->params['url']['data'])) {
			// render page
		} else {
			// do search
#			App::import('Vendor', 'rss', array('file' => 'RSS.php'));
			
			
#			$rss = new XML_RSS($uri);

#			$rss->parse();
			App::import('Vendor', 'rss_php');
			try {
				$rss_php = new rss_php;
				$rss_php->load($uri);
			} catch (Exception $e) {
				die($e);
			}
			$this->set('items', $rss_php->getItems());
		}
	}

	public function login(){
		
	}
}
?>